const paymentService = require('../utils/paymentService');
const Order = require('../models/Order');
const logger = require('../utils/logger');
const { validationResult } = require('express-validator');

/**
 * 创建支付订单
 * @route POST /api/payment/create
 * @access Private
 */
exports.createPayment = async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        status: 'error',
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { orderId, paymentMethod } = req.body;
    const userId = req.user.id;

    // 获取订单信息
    const order = await Order.findById(orderId).populate('service');
    if (!order) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }

    // 验证订单所有权
    if (order.user.toString() !== userId) {
      return res.status(403).json({
        status: 'error',
        message: '无权限操作此订单'
      });
    }

    // 验证订单状态
    if (order.status !== 'pending') {
      return res.status(400).json({
        status: 'error',
        message: '订单状态不允许支付'
      });
    }

    if (order.paymentStatus === 'paid') {
      return res.status(400).json({
        status: 'error',
        message: '订单已支付'
      });
    }

    // 创建支付订单
    const orderData = {
      orderId: order._id,
      amount: order.totalAmount,
      subject: `宠物护理服务 - ${order.service.name}`,
      userId
    };

    const paymentParams = await paymentService.createPayment(orderData, paymentMethod);

    res.status(200).json({
      status: 'success',
      message: '支付订单创建成功',
      data: {
        orderId: order._id,
        paymentId: paymentParams.paymentId,
        paymentMethod,
        amount: order.totalAmount,
        paymentParams
      }
    });

    logger.info(`用户 ${userId} 创建支付订单: ${orderId}`);
  } catch (error) {
    logger.error('创建支付订单失败:', error);
    res.status(500).json({
      status: 'error',
      message: '创建支付订单失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

/**
 * 查询支付状态
 * @route GET /api/payment/status/:paymentId
 * @access Private
 */
exports.getPaymentStatus = async (req, res) => {
  try {
    const { paymentId } = req.params;
    const userId = req.user.id;

    // 查找订单
    const order = await Order.findOne({ paymentId });
    if (!order) {
      return res.status(404).json({
        status: 'error',
        message: '支付订单不存在'
      });
    }

    // 验证订单所有权
    if (order.user.toString() !== userId) {
      return res.status(403).json({
        status: 'error',
        message: '无权限查看此支付订单'
      });
    }

    // 查询第三方支付状态
    let paymentStatus;
    try {
      paymentStatus = await paymentService.queryPaymentStatus(paymentId, order.paymentMethod);
    } catch (error) {
      logger.error(`查询支付状态失败: ${paymentId}`, error);
      // 如果第三方查询失败，返回数据库中的状态
      paymentStatus = {
        status: order.paymentStatus,
        message: '查询第三方支付状态失败，返回本地状态'
      };
    }

    res.status(200).json({
      status: 'success',
      data: {
        orderId: order._id,
        paymentId,
        paymentMethod: order.paymentMethod,
        paymentStatus: order.paymentStatus,
        orderStatus: order.status,
        amount: order.totalAmount,
        paidAt: order.paidAt,
        thirdPartyStatus: paymentStatus
      }
    });
  } catch (error) {
    logger.error('查询支付状态失败:', error);
    res.status(500).json({
      status: 'error',
      message: '查询支付状态失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

/**
 * 处理支付宝支付回调
 * @route POST /api/payment/alipay/notify
 * @access Public
 */
exports.handleAlipayNotify = async (req, res) => {
  try {
    const success = await paymentService.handleAlipayNotify(req.body);
    
    if (success) {
      res.status(200).send('success');
    } else {
      res.status(400).send('fail');
    }
  } catch (error) {
    logger.error('处理支付宝回调失败:', error);
    res.status(500).send('fail');
  }
};

/**
 * 处理微信支付回调
 * @route POST /api/payment/wechat/notify
 * @access Public
 */
exports.handleWechatNotify = async (req, res) => {
  try {
    const xmlData = req.body;
    const success = await paymentService.handleWechatNotify(xmlData);
    
    if (success) {
      res.status(200).type('application/xml').send('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
    } else {
      res.status(400).type('application/xml').send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>');
    }
  } catch (error) {
    logger.error('处理微信支付回调失败:', error);
    res.status(500).type('application/xml').send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统错误]]></return_msg></xml>');
  }
};

/**
 * 申请退款
 * @route POST /api/payment/refund
 * @access Private
 */
exports.requestRefund = async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        status: 'error',
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { orderId, refundAmount, reason } = req.body;
    const userId = req.user.id;

    // 获取订单信息
    const order = await Order.findById(orderId);
    if (!order) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }

    // 验证订单所有权
    if (order.user.toString() !== userId) {
      return res.status(403).json({
        status: 'error',
        message: '无权限操作此订单'
      });
    }

    // 验证订单状态
    if (order.paymentStatus !== 'paid') {
      return res.status(400).json({
        status: 'error',
        message: '订单未支付，无法退款'
      });
    }

    if (order.refundStatus === 'processing' || order.refundStatus === 'completed') {
      return res.status(400).json({
        status: 'error',
        message: '订单已申请退款或已退款'
      });
    }

    // 验证退款金额
    if (refundAmount > order.totalAmount) {
      return res.status(400).json({
        status: 'error',
        message: '退款金额不能超过订单金额'
      });
    }

    // 申请退款
    const refundResult = await paymentService.requestRefund(orderId, refundAmount, reason);

    res.status(200).json({
      status: 'success',
      message: '退款申请提交成功',
      data: {
        orderId,
        refundId: refundResult.refundId,
        refundAmount,
        reason,
        refundStatus: 'processing'
      }
    });

    logger.info(`用户 ${userId} 申请退款: ${orderId}, 金额: ${refundAmount}`);
  } catch (error) {
    logger.error('申请退款失败:', error);
    res.status(500).json({
      status: 'error',
      message: '申请退款失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

/**
 * 获取用户支付记录
 * @route GET /api/payment/records
 * @access Private
 */
exports.getPaymentRecords = async (req, res) => {
  try {
    const userId = req.user.id;
    const {
      page = 1,
      limit = 10,
      paymentMethod,
      paymentStatus,
      startDate,
      endDate
    } = req.query;

    // 构建查询条件
    const query = { user: userId };
    
    if (paymentMethod) {
      query.paymentMethod = paymentMethod;
    }
    
    if (paymentStatus) {
      query.paymentStatus = paymentStatus;
    }
    
    if (startDate || endDate) {
      query.createdAt = {};
      if (startDate) {
        query.createdAt.$gte = new Date(startDate);
      }
      if (endDate) {
        query.createdAt.$lte = new Date(endDate);
      }
    }

    // 分页查询
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const orders = await Order.find(query)
      .populate('service', 'name category')
      .populate('caregiver', 'name avatar')
      .select('paymentId paymentMethod paymentStatus totalAmount paidAt refundStatus refundAmount createdAt service caregiver')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    const total = await Order.countDocuments(query);

    res.status(200).json({
      status: 'success',
      data: {
        records: orders,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(limit),
          total,
          pages: Math.ceil(total / parseInt(limit))
        }
      }
    });
  } catch (error) {
    logger.error('获取支付记录失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取支付记录失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

/**
 * 获取支付统计信息
 * @route GET /api/payment/stats
 * @access Private
 */
exports.getPaymentStats = async (req, res) => {
  try {
    const userId = req.user.id;
    const { period = '30d' } = req.query;

    // 计算时间范围
    let startDate;
    const endDate = new Date();
    
    switch (period) {
      case '7d':
        startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
        break;
      case '30d':
        startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
        break;
      case '90d':
        startDate = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
        break;
      case '1y':
        startDate = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000);
        break;
      default:
        startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    }

    // 聚合查询
    const stats = await Order.aggregate([
      {
        $match: {
          user: userId,
          createdAt: { $gte: startDate, $lte: endDate }
        }
      },
      {
        $group: {
          _id: null,
          totalOrders: { $sum: 1 },
          paidOrders: {
            $sum: { $cond: [{ $eq: ['$paymentStatus', 'paid'] }, 1, 0] }
          },
          totalAmount: {
            $sum: { $cond: [{ $eq: ['$paymentStatus', 'paid'] }, '$totalAmount', 0] }
          },
          refundedAmount: {
            $sum: { $cond: [{ $eq: ['$refundStatus', 'completed'] }, '$refundAmount', 0] }
          },
          alipayOrders: {
            $sum: { $cond: [{ $eq: ['$paymentMethod', 'alipay'] }, 1, 0] }
          },
          wechatOrders: {
            $sum: { $cond: [{ $eq: ['$paymentMethod', 'wechat'] }, 1, 0] }
          }
        }
      }
    ]);

    const result = stats[0] || {
      totalOrders: 0,
      paidOrders: 0,
      totalAmount: 0,
      refundedAmount: 0,
      alipayOrders: 0,
      wechatOrders: 0
    };

    // 计算支付成功率
    result.paymentSuccessRate = result.totalOrders > 0 
      ? (result.paidOrders / result.totalOrders * 100).toFixed(2)
      : 0;

    res.status(200).json({
      status: 'success',
      data: {
        period,
        stats: result
      }
    });
  } catch (error) {
    logger.error('获取支付统计失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取支付统计失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

/**
 * 获取支持的支付方式
 * @route GET /api/payment/methods
 * @access Public
 */
exports.getPaymentMethods = async (req, res) => {
  try {
    const paymentMethods = [
      {
        code: 'alipay',
        name: '支付宝',
        icon: '/images/payment/alipay.png',
        enabled: !!process.env.ALIPAY_APP_ID,
        description: '支持支付宝余额、银行卡等多种支付方式'
      },
      {
        code: 'wechat',
        name: '微信支付',
        icon: '/images/payment/wechat.png',
        enabled: !!process.env.WECHAT_APP_ID,
        description: '支持微信钱包、银行卡等多种支付方式'
      }
    ];

    res.status(200).json({
      status: 'success',
      data: {
        paymentMethods: paymentMethods.filter(method => method.enabled)
      }
    });
  } catch (error) {
    logger.error('获取支付方式失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取支付方式失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};